import { useState, useEffect } from "react";
const wsUri = "ws://127.0.0.1:22003";
import { websopen, websclose, opendev, closedev, register, disregister } from '@/utils/ws'

export const useFingerInput = () => {
    const [fingerUrl, setFingerUrl] = useState<string>("");
    const [fingerState, setFingerState] = useState<string>('设备初始化中...');

    function onMessage(evt) {
        var jsondata = JSON.parse(evt.data);
        if (jsondata.datatype === "image") {
            var tempImg = jsondata.data.jpg_base64
            if (tempImg == undefined || tempImg == '') {
                return false
            }
            var strImgData = "data:image/jpg;base64,";
            strImgData += tempImg;
            console.log(strImgData);
            setFingerUrl(strImgData)
            return;
        } else {
            console.log(evt.data)
            return false;
        }
    }
    function onOpen() {
        opendev()
        setFingerState('设备初始化完毕，可以进行指纹录入')
        console.log("设备开启成功");
    }

    function onClose() {
        closedev()
        console.log("设备断开成功");
    }

    function onError() {
        closedev()
        setFingerState('设备出错，请检查设备连接是否正常！')
        console.error('设备出错，请检查设备连接是否正常！')
    }
    function clearFinger() {
        setFingerUrl("")
    }
    const onRegister = () => {
        setFingerState('采集中...')
        register()
    }

    const onDisregister = () => {
        setFingerState('设备初始化完毕，可以开始采集指纹')
        disregister()
    }
    useEffect(() => {
        websopen({ onMessage, onOpen, onClose, onError })

        return () => {
            websclose()
        }
    }, [])
    return { fingerState, fingerUrl, onRegister, onDisregister, clearFinger }
}